package com.by.test.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 * 因为不属于controller层，也不属于service层，所以用component注解来存放到IOC容器里
 */
@Component
public class AliyunOSSUtils {
    // 直接通过@Value注入Nacos中的配置
    @Value("${spring.aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${spring.aliyun.oss.access-key-id}")
    private String accessKeyId;

    @Value("${spring.aliyun.oss.access-key-secret}")
    private String accessKeySecret;

    @Value("${spring.aliyun.oss.bucket-name}")
    private String bucketName;

    private OSS ossClient;

    // 初始化OSS客户端
    @PostConstruct
    public void init() {
        // 创建OSS客户端实例
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 检查存储桶是否存在，不存在则创建
        if (!ossClient.doesBucketExist(bucketName)) {
            ossClient.createBucket(bucketName);
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        }
    }



    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        // 安全构建URL：阿里云OSS的访问格式固定为 https://bucketName.endpoint/filename
        return String.format("https://%s.%s/%s", bucketName, endpoint, fileName);
    }
}
